/*
 * This is Image Search adapter class.It takes text as input and returns/outputs the respective image.
 */

package com.oops.appquery;
import java.awt.BorderLayout;
import java.awt.Image;
import java.io.DataInputStream;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.json.JSONArray;
import org.json.JSONObject;

public class ImageSearch {
	
	public ImageSearch(String text)throws Exception{
		framework obj=new framework();
		@SuppressWarnings("deprecation")
		String line= (new DataInputStream(obj.gsearch("http://ajax.googleapis.com/ajax/services/search/images?v=1.0&"
			    + "q="+ text.replace(" ", "%20"))).readLine());
		getImagelinks(line);
	}
	public void getImagelinks(String line) throws Exception
    {
 	   JSONObject json = new JSONObject(line);
		JSONObject gson=json.getJSONObject("responseData");
		JSONArray kson=gson.getJSONArray("results");
		int size=kson.length();
		for(int i=0;i<size;i++)
		{
			JSONObject lson=kson.getJSONObject(i);
			String sample=lson.getString("url")	;
					
			System.out.println(sample);
			URL url = new URL(sample);
			
		    Image image = ImageIO.read(url);
			JFrame frame = new JFrame();
			JLabel label = new JLabel(new ImageIcon(image));
			frame.getContentPane().add(label, BorderLayout.CENTER);
			frame.pack();
			frame.setVisible(true);
			//System.out.println(x.readLine());
			
		}
    }
}


